<template>
  <div>
    <!-- 搜索栏 ： 两个搜索框  搜索按钮  添加订单按钮  批量删除   -->
	<el-row>
	  <el-col :span="1"></el-col>
	  <el-col :span="4">
		   <el-input placeholder="请输入用户名搜索" v-model="query.username"/>
	  </el-col>
	  <el-col :span="4">
	  		<el-input placeholder="请输入订单号搜索" v-model="query.orderNumber"/>
	  </el-col>
	  <el-col :span="5">
		<el-select v-model="query.businessId" 
					placeholder="请选择商家" >
			<el-option label="请选择商家" :value="null" />
			<el-option
				v-for="business in allBusinessList"
				:key="business.businessId"
				:label="business.businessName"
				:value="business.businessId"
			/>
		</el-select>
	  </el-col>
	  <el-col :span="4">
		<el-select v-model="query.orderState" 
					placeholder="请选择状态" >
			<el-option label="请选择状态" :value="null" />
			<el-option label="未支付" :value="0" />
			<el-option label="已支付" :value="1" />
		</el-select>
	  </el-col>
	  
    </el-row>
	<el-row>
		<el-col :span="1"></el-col>
		<el-col :span="9">
		<!-- 日期区间组件 -->
		<el-date-picker
			v-model="dateCondition"
			type="datetimerange"
			start-placeholder="开始时间"
			end-placeholder="结束时间"
			format="YYYY-MM-DD HH:mm:ss"
			date-format="YYYY/MM/DD ddd"
			time-format="A hh:mm:ss"
			value-format="YYYY-MM-DD HH:mm:ss"
			@change="dateConditionChange"
		/>
	  </el-col>
	  <el-col :span="2">
	  		<el-button type="primary" plain @click="getByPage">搜索</el-button>
	  </el-col>
	  <el-col :span="3">
	  		<el-button type="danger" plain @click="handleBatchDel">批量删除</el-button>
	  </el-col>
	</el-row>
  
	<!-- 表格 -->
	<el-row>
	  <el-col :span="1"></el-col>
	  <el-col :span="22">
		  
		<el-table :data="pb.data" 
		          stripe 
				  border
				  @selection-change="handleSelectionChange">
		  <!-- 表格的可展开部分   展开部分显示订单详情的内容 -->
		  <el-table-column type="expand">
			<template #default="scope">
				<div m="4">
				<p m="t-0 b-2">订单编号: {{ scope.row.orderNumber }}</p>
				<p m="t-0 b-2">下单时间: {{ scope.row.orderDate }}</p>
				<p m="t-0 b-2">送货地址: {{ scope.row.address.address }}</p>
				<h3>订单详情</h3>
				<el-table :data="scope.row.orderDetailList" border>
					<el-table-column label="餐品名称" prop="food.foodName" />
					<el-table-column label="数量" prop="quantity" />
				</el-table>
				</div>
			</template>
			</el-table-column>
		  <el-table-column type="selection"  width="40" />
		  <!-- <el-table-column type="index" width="50" /> -->
		  <el-table-column prop="orderNumber" label="订单编号" width="100px" show-overflow-tooltip/>
		  <el-table-column prop="orderDate" label="下单时间" width="120px" show-overflow-tooltip/>
		  <el-table-column prop="user.userName" label="用户名" width="120px"/>
		  <el-table-column prop="business.businessName" label="商家名称" width="120px"/>
		  <el-table-column prop="address.contactName" label="联系人" width="120px"/> 
		  <el-table-column prop="address.address" label="送货地址" width="120px" show-overflow-tooltip/>
		  <el-table-column label="总价">
			  <template #default="scope">
				  ￥{{scope.row.orderTotal}}
			  </template>
		  </el-table-column>
		  <el-table-column label="状态" width="120px">
			  <template #default="scope">
				  {{scope.row.orderState==0?'未支付':'已支付'}}
			  </template>
		  </el-table-column>
		  <el-table-column label="操作" width="200px">
		        <template #default="scope">
		          <el-button size="small" @click="handleEdit(scope.row)">
		            编辑
		          </el-button>
		          <el-button
		            size="small"
		            type="danger"
		            @click="handleDelete(scope.row.orderId)"
		          >
		            删除
		          </el-button>
		        </template>
		      </el-table-column>
		</el-table>
		  
	  </el-col>
	  
	</el-row>  
	
	<!-- 分页组件 -->
	<el-row>
	  <el-col :span="6"></el-col>
	  <el-col :span="12">
		   <el-pagination
		        v-model:current-page="query.pageNow"
		        v-model:page-size="query.pageCount"
		        :page-sizes="[5, 8, 10, 20]"
		        layout="total, sizes, prev, pager, next, jumper"
		        :total="pb.totalRows"
		        @size-change="getByPage"
		        @current-change="getByPage"
		      />
	  </el-col>
	  
	</el-row>  
	
	<!-- 编辑订单信息的对话框  用于添加和修改 -->
	<el-dialog v-model="dialogFormVisible" title="编辑订单信息" width="500" draggable>
		<el-form :model="form">
		  <el-form-item label="订单编号" :label-width="formLabelWidth">
			<el-input v-model.trim="form.orderNumber" autocomplete="off" readonly/>
		  </el-form-item>
		  <el-form-item label="下单时间" :label-width="formLabelWidth">
			<el-input v-model.trim="form.orderDate" autocomplete="off" readonly/>
		  </el-form-item>
		  <el-form-item label="下单用户" :label-width="formLabelWidth">
			  <el-input v-model.trim="form.user.userName" autocomplete="off" readonly/>
		  </el-form-item>
		  <el-form-item label="送货地址" :label-width="formLabelWidth">
			<el-select v-model="form.addressId" placeholder="请选择送货地址" style="width: 240px">
				<el-option
					v-for="address in userAddressList"
					:key="address.addressId"
					:label="address.contactName"
					:value="address.addressId"
					>
					<span style="float: left">{{ address.contactName }}|{{address.contactTel}}</span>
					<span
						style="
						float: right;
						color: var(--el-text-color-secondary);
						font-size: 13px;
						"
					>
						{{ address.address }}
					</span>
				</el-option>
			</el-select>
		  </el-form-item>
		  <el-form-item label="订单状态" :label-width="formLabelWidth">
				<el-switch
					v-model="form.orderState"
					active-text="已支付"
					inactive-text="未支付"
					:active-value="1"
					:inactive-value="0"
				/>
		  </el-form-item>
		</el-form>
		<template #footer>
		  <div class="dialog-footer">
			<el-button @click="dialogFormVisible = false">取消</el-button>
			<el-button type="primary" @click="addOrUpdate">
			  确认提交
			</el-button>
		  </div>
		</template>
  </el-dialog>
	
  </div>
</template>

<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import { nanoid } from 'nanoid';
import { Plus } from '@element-plus/icons-vue'

  let {proxy} = getCurrentInstance();

  /*
  -------接收日期条件选择的值   组数 包含开始和结束的日期时间-------------
	["2024-11-01 12:00:00","2024-11-27 12:00:00"]
  */
  let dateCondition = ref('');

  //监听到日期选择的变化  获取数组中两个值  给条件中的lowDate和highDate来进行赋值
  const dateConditionChange = (value)=>{
		console.log('日期变化---',value);
		if(value){
			query.value.lowDate = value[0];
			query.value.highDate = value[1];
		}else{
			query.value.lowDate = null;
			query.value.highDate = null;
		}
  }

  //对话框是否显示
  let dialogFormVisible = ref(false);
  let formLabelWidth = ref('100px');
  
  //表单数据 添加和修改
  let form = ref({
	  orderAccount: '',
	  orderName: '',
	  orderAddress: '',
	  /* orderImg: '', */
	  orderExplain: '',
	  startPrice: 0.0,
	  deliveryPrice: 0.0,
	  remarks: ''
  })
  
  //生成订单账号的函数
  const generateAccount = ()=>{
	  let account = nanoid().replaceAll("_","").replaceAll("-","");
	  console.log(account);
	  let startIndex = Math.floor(Math.random()*10);
	  account = account.substring(startIndex,startIndex+9);
	  console.log(account);
	  return account;
  }
  
  //点新增订单信息按钮弹出对话框
  const showDialog = ()=>{
	  
	  dialogFormVisible.value = true;
	  //数据清除
	  form.value = {
		  orderAccount: generateAccount(),
		  orderName: '',
		  orderAddress: '',
		  orderExplain: '',
		  orderImg: '',
		  startPrice: 0.0,
		  deliveryPrice: 0.0,
		  remarks: ''
	  };
	  //清空之前上传的图片的回显链接
	  imageUrl.value = '';
  }

  //分页+搜索条件
  let query = ref({
	  pageNow: 1,
	  pageCount: 5,
	  userName: '',
	  orderNumber: '',
	  businessId: null,
	  orderState: null,
	  lowDate: null,
	  highDate: null
  })
  
  //分页对象 totalRows  totalPages  data(集合)
  let pb = ref({
	  totalRows: 0,
	  totalPages: 0,
	  data: []
  })

  const getByPage = ()=>{
	  proxy.$axios({
		  method: 'post',
		  url: '/order/page',
		  data: query.value
	  }).then(res=>{
		  console.log(res);
		  let resultBean = res.data;
		  if(resultBean.code==200){
			let pageBean = resultBean.data; 
			pb.value = pageBean;// totalRows  totalPages  data(集合)
		  }else{
			  ElMessage.error(resultBean.msg);
		  }
	  })
  }
  
  //添加或修改
  const addOrUpdate = ()=>{

	console.log('准备修改----',form.value);
	//form对象里有user、address、business、orderDetailList对象  去掉之后再提交
	//delete 对象.属性名
	//解构
	const {user,address,business,orderDetailList,...newForm} = form.value
	console.log(newForm);

	  //订单模块中controller没有做添加和修改的请求合并  所以访问修改的接口
	  proxy.$axios({
		  method: 'put',
		  url: '/order',
		  data: newForm
	  }).then(res=>{
		  let resultBean = res.data;
		  if(resultBean.code == 200){
			  getByPage();
			  dialogFormVisible.value = false;
			  ElMessage.success('保存订单信息成功');
		  }else{
			  ElMessage.error(resultBean.msg);
		  }
	  })
  }

  //当前订单用户的地址集合
  const userAddressList = ref([])
  
  //处理数据回显
  const handleEdit = (order)=>{
	  console.log('回显：order----',order);
	  form.value = Object.assign({},order);

	  proxy.$axios({
		method: 'get',
		url: '/address/user/'+order.userId
	  }).then(res=>{
		let resultBean = res.data;
		if(resultBean.code == 200){
			userAddressList.value = resultBean.data;
			//打开对话框
			dialogFormVisible.value = true;
		}else{
			ElMessage.error(resultBean.msg);
		}
	  })
  }
  
  //处理删除
  const handleDelete = (orderId)=>{
	  console.log('删除：orderId----',orderId);
	  ElMessageBox.confirm(
	      '您确定要删除该订单信息吗？',
	      '删除提示',
	      {
	        confirmButtonText: '确定',
	        cancelButtonText: '取消',
	        type: 'warning',
	      }
	    )
	      .then(() => {
			  
			  //确定删除
			  proxy.$axios({
				  method: 'delete',
				  url: '/order/'+orderId
			  }).then(res=>{
				  let resultBean = res.data;
				  if(resultBean.code == 200){
					  ElMessage.success('删除成功');
					  getByPage();
				  }else{
					  ElMessage.error(resultBean.msg);
				  }
			  })
			  
	      })
	      .catch(() => {
	           ElMessage.info('取消删除');
	      })
  }
  
  // const selectable = (row,index)=>{
	 //  console.log('selectable',row,index);
	 //  return true;
  // }
  
  //选中项的id集合
  let selectOptions = ref([]);
  
  //表格中多选框选中或取消时会触发  也就是选中项变化
  const handleSelectionChange = (newSelection)=>{
	  console.log('选中项改变',newSelection);
	  selectOptions.value = []; //清空
	  newSelection.forEach((selOp)=>{
		  console.log(selOp.orderId);
		  selectOptions.value.push(selOp.orderId);
	  });
  }
  
  //批量删除的函数
  const handleBatchDel = ()=>{
	  console.log(selectOptions.value);
	  if(selectOptions.value.length==0){
		  ElMessage.info('请选中至少一条记录之后再进行删除');  
		  return;
	  }
	  
	  ElMessageBox.confirm(
	      '您确定要删除选中的订单信息吗？',
	      '删除提示',
	      {
	        confirmButtonText: '确定',
	        cancelButtonText: '取消',
	        type: 'warning',
	      }
	    )
	      .then(() => {

			console.log(selectOptions.value);
			console.log(typeof(selectOptions.value));
			console.log(JSON.stringify(selectOptions.value));

			let str = JSON.stringify(selectOptions.value);
			str = str.substring(1,str.length-1);
	  			  
	  			  //确定删除
				proxy.$axios({
					method: 'post',
					url: '/order/batch/'+str,
				}).then(res=>{
					let resultBean = res.data;
					if(resultBean.code == 200){
						ElMessage.success('删除成功');  
						getByPage();
					}else{
						ElMessage.error(resultBean.msg);
					}
				})
	  			
	  			  
	      })
	      .catch(() => {
	           ElMessage.info('取消删除');
	      })
  }
  
  //上传图片的回显链接
  let imageUrl = ref('');
  
  //上传成功之后的回调
  const handleAvatarSuccess = (response,uploadFile)=>{
	  ElMessage.success('上传成功');
	  console.log('上传成功，',response,uploadFile);
	  //负责上传完成 图片回显
	  imageUrl.value = response.data;
	  //将上传成功的链接放入form表单， 添加或修改时会携带到服务端
	  form.value.orderImg = response.data;
  }
  
  //上传之前预检文件
  const beforeAvatarUpload = (rawFile)=>{
	  //文件类型不符合要求 或者 文件大小超过要求  都不能上传
	  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
	      ElMessage.error('Avatar picture must be JPG format!')
	      return false
	    } else if (rawFile.size / 1024 / 1024 > 5) {
	      ElMessage.error('Avatar picture size can not exceed 5MB!')
	      return false
	    }
		//可以上传
	    return true
  }

  //-----存储所有商家的集合-----------
  const allBusinessList = ref([]);


  //--------查询所有商家----------
  const getAllBusiness = ()=>{
	proxy.$axios({
		method: 'get',
		url: '/business/all'
	}).then(res=>{
		let resultBean = res.data;
		if(resultBean.code == 200){
			allBusinessList.value = resultBean.data;
		}
	})
  }
  
  onMounted(()=>{
	  getByPage();
	  getAllBusiness();
  })


</script>

<style scoped>
	.avatar-uploader .avatar {
	  width: 100px;
	  height: 100px;
	  display: block;
	}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>